package com.mk.config;

import com.mk.filter.JwtAuthenticationTokenFilter;
import com.mk.service.impl.UserServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Security配置类
 */
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
public class SecurityConfig {

    private final UserServiceImpl userService;

    private final JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * Security过滤器链
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            //禁用明文验证
            .httpBasic(AbstractHttpConfigurer::disable)
            //关闭csrf（基于token）
            .csrf(AbstractHttpConfigurer::disable)
            //禁用默认登录页
            .formLogin(AbstractHttpConfigurer::disable)
            //禁用默认登出页
            .logout(AbstractHttpConfigurer::disable)
            //禁用session（基于token）
            .sessionManagement(session -> session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            //配置拦截信息
            .authorizeHttpRequests(authorizeRequests -> authorizeRequests
                .requestMatchers("/admin/officer/login", "/user/register", "/user/login/password").permitAll()
                .requestMatchers(HttpMethod.OPTIONS).permitAll()
                .anyRequest().authenticated())
            //注册重写后的UserDetailsService实现
            .userDetailsService(userService)
            //注册自定义的过滤器
            .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }

    /**
     * 配置认证提供者
     * 使用 DaoAuthenticationProvider，它依赖于 UserDetailsService 和 PasswordEncoder
     */
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        // 设置自定义的 UserDetailsService
        authProvider.setUserDetailsService(userService);
        // 设置密码编码器
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    /**
     * 配置认证管理器
     * 用于执行认证过程，例如在登录时调用
     * @param authConfig
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    /**
     * BCrypt算法加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

}
